package com.hmdp;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.PasswordEncoder;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 获取千人登陆的 token ，基于原有的 userServiceImpl 修改
 * </p>
 *
 * @author chenpi
 * @since 2024-10-22
 */
@Service
@Slf4j
public class GetUserTokenService extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 2. 保存验证码到 redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // session.setAttribute(phone, code);
        // 3. 发送验证码
        log.debug("发送短信验证码成功，验证码：{}", code);
        // 4. 返回成功
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 从 redis 获取验证码并校验
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();

        // 校验验证码
        String cacheCode = "123456";
        // stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (StrUtil.isNotBlank(cacheCode)) {
            // stringRedisTemplate.delete(LOGIN_CODE_KEY + phone);
            if (!cacheCode.equals(loginForm.getCode())) {
                return Result.fail("验证码错误");
            }
            // 验证码登录成功
            return handleSmsLogin(phone);
        }
        if (StrUtil.isNotBlank(password)) {
            // 密码登录
            return handlePasswordLogin(phone, password);
        }
        return Result.fail("登录失败");
    }

    @Override
    public Result logout(HttpServletRequest request) {
        // 1.从请求头中获取token
        String token = request.getHeader("authorization");
        // 2.获取当前用户信息
        String nickName = UserHolder.getUser().getNickName();
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        log.info(LocalTime.now() + "用户：{}，退出成功", nickName);
        return Result.ok();
    }

    @Override
    public Result sign() {
        return null;
    }

    @Override
    public Result signCount() {
        return null;
    }

    public Result handleSmsLogin(String phone) {
        // 2. 判断用户是否存在
        User user = query().eq("phone", phone).one();

        if (user == null) {
            // 新用户注册
            user = new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
            try {
                save(user);
            } catch (Exception e) {
                log.error("新用户注册失败: {}", e.getMessage(), e);
                return Result.fail("系统错误，请稍后再试");
            }
        }

        // 3. 保存用户到 redis
        return saveUserToRedis(user);
    }

    private Result handlePasswordLogin(String phone, String password) {
        // 2. 判断用户是否存在并验证密码
        User user = query().eq("phone", phone).one();

        if (user == null) {
            log.warn("用户不存在: {}", phone);
            return Result.fail("用户不存在");
        }

        // 验证密码
        String pwd = user.getPassword();
        if (StrUtil.isBlank(pwd)) {
            return Result.fail("用户未设置密码");
        }
        if (!PasswordEncoder.matches(password, pwd)) {
            log.warn("密码错误: {}", phone);
            return Result.fail("密码错误");
        }

        // 3. 保存用户到 redis
        return saveUserToRedis(user);
    }

    private Result saveUserToRedis(User user) {
        // 3.1. 生成随机 token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 3.2. 将用户信息转为 JSON 存入 redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        /*Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(userDTO.getId()));
        map.put("nickName", userDTO.getNickName());
        map.put("icon", userDTO.getIcon());*/

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        // 3.3. 设置 token 的过期时间
        // stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 把生成的token给写入到token.txt文件中
        try {
            Files.write(Paths.get("token.txt"), (token + "\n").getBytes(),StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            // 处理文件写入时可能出现的异常
            System.err.println("无法写入文件: " + e.getMessage());
        }


        return Result.ok(token);
    }


}
